import { businessTypeList, discountAdd, discountUpdate } from "@/services/chargingManage";
import { Drawer, Form, Button, Row, Col, Input, Select, DatePicker, Divider, Modal, Radio, InputNumber, message} from "antd";
import moment from "moment";
import React from "react";
import { formatMessage } from 'umi-plugin-react/locale';

class discountModal extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      visible:false,
      id:null,
      businessList:[]
    }
  }

  componentDidMount(){
    if(this.props.onRef){
      this.props.onRef(this)
    }
  }

  initModal = data => {
    this.getBusinessList()
    this.setState({
      visible:true,
      id:data?.id
    },() => {
      if(data){
        this.props.form.setFieldsValue({
          code:data.code,
          name:data.name,
          type:data.type,
          discountType:data.price !== '' && data.price !== null && data.price !== undefined ? 0 : 1,
          settlementId:data.settlementId,
          startDate:data.startDate ? moment(data.startDate) : null,
          endDate:data.endDate ? moment(data.endDate) : null,
          usePrice:data.usePrice,
          remainingPrice:data.remainingPrice
        })
        setTimeout(() => {
          if(data.price !== '' && data.price !== null && data.price !== undefined){
            this.props.form.setFieldsValue({price:data.price})
          }else{
            this.props.form.setFieldsValue({rate:data.rate})
          }
        },100)
      }
    })
  }

  onClose = () => {
    this.props.form.resetFields()
    this.setState({
      visible:false,
      id:null
    })
  }

  okValidate = () => {
    this.props.form.validateFields((error,values) => {
      if(!error){
        values.startDate = values.startDate ? moment(values.startDate).format("YYYY-MM-DD") : ''
        values.endDate = values.endDate ? moment(values.endDate).format("YYYY-MM-DD") : ''
        if(values.discountType == 0){
          values.rate = null
        }else{
          values.price = null
        }
        this.doSave(values)
      }
    })
  }

  doSave = async values => {
    let res = {}
    if(this.state.id){
      values.id = this.state.id
      res = await discountUpdate(values)
    }else{
      res = await discountAdd(values)
    }
    if(res.code == -1){
      return false
    }
    message.info(res.message)
    this.onClose()
    this.props.refreshList()
  }

  disabledEndDate = endValue => {
    const startValue = this.props.form.getFieldValue("startDate")
    
    if (!endValue || !startValue) {
      return false;
    }
    return endValue.valueOf() <= startValue.valueOf();
  };

  getBusinessList = async () => {
    const res = await businessTypeList()
    this.setState({businessList:res.settlement})
  }

  render(){
    const { visible,id,businessList, } = this.state
    const { form:{getFieldDecorator,getFieldValue,resetFields} } = this.props;
    const formItemLayout = {
      labelCol: { span: 3 },
      wrapperCol: { span: 16 },
    };

    return (
      <Drawer
        title={formatMessage({ id: 'chargingManage.discountManage.discountModal.manageDiscount' })}
        visible={visible}
        onClose={this.onClose}
        width={'100%'}
        destroyOnClose
      >
        <Form {...formItemLayout} className="normalForm">
          <Form.Item label={formatMessage({ id: 'chargingManage.discountManage.discountModal.code' })}>
            {getFieldDecorator("code",{rules:[{required:true,message:formatMessage({ id: 'chargingManage.discountManage.discountModal.pleaseInput' })}]})(
              <Input maxLength={8} placeholder="8位数流水码" />
            )}
          </Form.Item>
          <Form.Item label={formatMessage({ id: 'chargingManage.discountManage.discountModal.planName' })}>
            {getFieldDecorator("name",{rules:[{required:true,message:formatMessage({ id: 'chargingManage.discountManage.discountModal.pleaseInput' })}]})(
              <Input />
            )}
          </Form.Item>
          <Form.Item label={formatMessage({ id: 'chargingManage.discountManage.discountModal.type' })}>
            {getFieldDecorator("type")(
              <Select>
                <Select.Option value={0}>{formatMessage({ id: 'chargingManage.discountManage.discountModal.discountAllowance' })}</Select.Option>
                <Select.Option value={1} disabled>{formatMessage({ id: 'chargingManage.discountManage.discountModal.promotionCode' })}</Select.Option>
                <Select.Option value={2} disabled>{formatMessage({ id: 'chargingManage.discountManage.discountModal.voucher' })}</Select.Option>
              </Select>
            )}
          </Form.Item>
          <Form.Item label=" " colon={false}>
            {getFieldDecorator("discountType",{initialValue:0})(
              <Radio.Group>
                <Radio value={0}>{formatMessage({ id: 'chargingManage.discountManage.discountModal.amount' })}</Radio>
                <Radio value={1}>{formatMessage({ id: 'chargingManage.discountManage.discountModal.discountRate' })}</Radio>
              </Radio.Group>
            )}
          </Form.Item>
          {
            getFieldValue("discountType") == 0 ? (
              <Form.Item label={formatMessage({ id: 'chargingManage.discountManage.discountModal.amount' })}>
                {getFieldDecorator("price")(
                  <InputNumber />
                )}
                <span>元</span>
              </Form.Item>
            ) : (
              <Form.Item label={formatMessage({ id: 'chargingManage.discountManage.discountModal.discountRate' })}>
                {getFieldDecorator("rate")(
                  <InputNumber max={100} precision={2} />
                )}
                %
              </Form.Item>
            )
          }
          <Form.Item label={formatMessage({ id: 'chargingManage.discountManage.discountModal.settlementParty' })}>
            {getFieldDecorator("settlementId")(
              <Select>
                {businessList.map(item => <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>)}
              </Select>
            )}
          </Form.Item>
          <Form.Item label={formatMessage({ id: 'chargingManage.discountManage.discountModal.validPeriod' })}>
            <Form.Item style={{display:"inline-block",marginBottom:0}}>
              {getFieldDecorator("startDate",{rules:[{required:true,message:"请选择"}]})(
                <DatePicker onChange={() => resetFields(["endDate"])} />
              )}
            </Form.Item>
            <span style={{margin:"0 10px"}}>{formatMessage({ id: 'chargingManage.discountManage.discountModal.to' })}</span>
            <Form.Item style={{display:"inline-block",marginBottom:0}}>
              {getFieldDecorator("endDate",{rules:[{required:true,message:"请选择"}]})(
                <DatePicker disabled={!getFieldValue("startDate")} disabledDate={this.disabledEndDate} />
              )}
            </Form.Item>
          </Form.Item>
          <Form.Item label={formatMessage({ id: 'chargingManage.discountManage.discountModal.actualAmount' })}>
            {getFieldDecorator("usePrice")(
              <InputNumber min={0} />
            )}
            <span>元</span>
          </Form.Item>
          <Form.Item label={formatMessage({ id: 'chargingManage.discountManage.discountModal.currentBalance' })}>
            {getFieldDecorator("remainingPrice")(
              <InputNumber min={0} />
            )}
            <span>元</span>
          </Form.Item>
        </Form>

        <div
          style={{
            position: 'absolute',
            right: 0,
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e9e9e9',
            padding: '10px 16px',
            background: '#fff',
            textAlign: 'right',
          }}
        >
          <Button onClick={this.onClose} style={{ marginRight: 8 }}>{formatMessage({ id: 'chargingManage.discountManage.discountModal.cancel' })}</Button>
          <Button onClick={this.okValidate} type="primary">{formatMessage({ id: 'chargingManage.discountManage.discountModal.save' })}</Button>
        </div>

      </Drawer>
    )
  }
}

export default Form.create()(discountModal)